<template>
  <div class="code-content-box">
    <div class="code-menu">
      <div
          class="code-menu-item"
          :class="{active: index === pageIndex}"
          v-for="(item, index) in props.dataList"
          :key="index"
          @click="pageIndex = index"
      >
        {{ item.label }}
      </div>
    </div>
    <High :code="code" />
    <div class="copy-btn">
      <div v-show="showCopied">Copied</div>
      <div class="copy" @click="copyCode">Copy</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import 'highlight.js/styles/stackoverflow-dark.css'
import "highlight.js/lib/common"
import high from "@highlightjs/vue-plugin"
const { component: High } = high

defineOptions({
  name: "CodeContent",
  inheritAttrs: false
})

const props = defineProps({
  dataList: {
    type: Array,
    default: () => []
  }
})

const pageIndex = ref(0)

const code = computed(() => {
  return props.dataList[pageIndex.value]?.code || '代码缺失'
})

const showCopied = ref(false)

function copyCode () {
  navigator.clipboard.writeText(code.value).then(() => {
    showCopied.value = true
    setTimeout(() => {
      showCopied.value = false
    }, 2000)
  })
}

</script>

<style scoped>
.code-content-box {
  width: 100%;
  position: relative;
}
.code-menu {
  display: flex;
  color: #ffffff;
  background-color: #1c1b1b;
}
.code-menu .code-menu-item {
  padding: 5px;
  cursor: pointer;
}
.code-menu .active {
  color: #f08d49;
  position: relative;
}
.code-menu .active::after {
  content: "";
  width: 100%;
  height: 3px;
  position: absolute;
  top: 100%;
  left: 0;
  background-color: #ffffff;
}
.code-content-box pre {
  margin-top: 0;
  line-height: 1.3;
}
.code-content-box .copy-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  color: #ffffff;
  font-size: 12px;
  display: none;
}
.code-content-box:hover .copy-btn {
  display: flex;
}
.code-content-box .copy-btn > div {
  padding: 10px;
  cursor: pointer;
  border-radius: 5px;
}
.code-content-box .copy-btn .copy:hover {
  background-color: rgba(255,255,255,.1);
}
</style>